<?php

// +----------------------------------------------------------------------
// | Think.Admin
// +----------------------------------------------------------------------
// | 版权所有 2014~2017 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://think.ctolog.com
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zoujingli/Think.Admin
// +----------------------------------------------------------------------

namespace controller;
use app\common\controller\BaseController;
use service\DataService;
use service\FileService;
use service\ToolsService;
use think\Controller;
use think\db\Query;
use think\Db;
use think\Request;

/**
 * 后台权限基础控制器
 * Class BasicAdmin
 * @package controller
 */
class BasicAdmin extends BaseController
{

    public $sort;
    public $order;
    public $list_relation = false;
    /**
     * 页面标题
     * @var string
     */
    public $title;

    /**
     * 默认操作数据表
     * @var string
     */
    public $table;

    /**
     * 默认检查用户登录状态
     * @var bool
     */
    public $checkLogin = true;

    /**
     * 默认检查节点访问权限
     * @var bool
     */
    public $checkAuth = true;



    protected function _initialize()
    {
        parent::_initialize();

    }
    /**
     * 表单默认操作
     * @param Query $dbQuery 数据库查询对象
     * @param string $tplFile 显示模板名字
     * @param string $pkField 更新主键规则
     * @param array $where 查询规则
     * @param array $extendData 扩展数据
     * @return array|string
     */
    protected function _form($dbQuery = null, $tplFile = '', $pkField = '', $where = [], $extendData = []){
       // $db = is_null($dbQuery) ? Db::name($this->table) : (is_string($dbQuery) ? Db::name($dbQuery) : $dbQuery);
        $db = is_null($dbQuery) ?  model($this->table) : (is_string($dbQuery) ? model($dbQuery) : $dbQuery);
        $pk = empty($pkField) ? ($db->getPk() ? $db->getPk() : 'id') : $pkField;
        $pkValue = $this->request->param($pk, isset($where[$pk]) ? $where[$pk] : (isset($extendData[$pk]) ? $extendData[$pk] : null));


        // 非POST请求, 获取数据并显示表单页面
        if (!$this->request->isPost()) {
            $info = ($pkValue !== null) ? array_merge((array)$db->where($pk, $pkValue)->where($where)->find()->toArray(), $extendData) : $extendData;
            if (false !== $this->_callback('_before', $info)) {
                empty($this->title) || $this->assign('title', $this->title);
                return $this->fetch($tplFile, ['info' => $info]);
            }
            return $info;
        }
        // POST请求, 数据自动存库
        $data = array_merge($this->request->post(), $extendData);
        if (false !== $this->_callback('_before', $data)) {
            $result = DataService::save($db, $data, $pk, $where);


            if (false !== $this->_callback('_after', $result)) {
                $result !== false ? $this->success('恭喜, 数据保存成功!', '') : $this->error('数据保存失败, 请稍候再试!');
            }
        }
    }

    /**
     * 列表集成处理方法
     * @param Query $dbQuery 数据库查询对象
     * @param bool $isPage 是启用分页
     * @param bool $isDisplay 是否直接输出显示
     * @param bool $total 总记录数
     * @return array|string
     */
    protected function _list($dbQuery = null, $isPage = true, $isDisplay = true, $total = false) {
        //D('SystemAd')->with('SystemAdBoard')->select()->toArray();
        //$db = is_null($dbQuery) ? D($this->table) : (is_string($dbQuery) ? D($dbQuery) : $dbQuery);
        $db = is_null($dbQuery) ?  model($this->table) : (is_string($dbQuery) ? model($dbQuery) : $dbQuery);

        $mod_pk = $db->getPk();
        if ($this->request->get("sort",'','trim')) {
            $sort = $this->request->get("sort",'', 'trim');
        } else if (!empty($sort_by)) {
            $sort = $sort_by;
        } else if ($this->sort) {
            $sort = $this->sort;
        } else {
            $sort = $mod_pk;
        }
        if ($this->request->get("order",'', 'trim')) {
            $order = $this->request->get("order",'', 'trim');
        } else if (!empty($order_by)) {
            $order = $order_by;
        } else if ($this->order) {
            $order = $this->order;
        } else {
            $order = 'DESC';
        }
        if(in_array($sort,$db->getTableFields())){
            $db->order($sort.' '.$order);
        }

        $this->list_relation && $db->with($this->list_relation);


        if($map = $this->_search()){
            $db->where($map);
        }
        $result = [];
        if ($isPage) {
            $rowPage = intval($this->request->get('rows', cookie('rows')));
            cookie('rows', $rowPage >= 10 ? $rowPage : 20);
            $page = $db->paginate($rowPage, $total, ['query' => $this->request->get()]);
            $result['list'] = $page->all();
            $result['page'] = preg_replace(['|href="(.*?)"|', '|pagination|'], ['data-open="$1" href="javascript:void(0);"', 'pagination pagination-sm pull-right'], $page->render());
        } else {
            $result['list'] = $db->select();
        }

        if (false !== $this->_callback('_after_list', $result['list']) && $isDisplay) {
            !empty($this->title) && $this->assign('title', $this->title);
            return $this->fetch('', $result);
        }


        return $result;
    }
    /**
     * 获取请求参数生成条件数组
     */
    protected function _search($dbQuery = null) {
        //生成查询条件
        $mod = is_null($dbQuery) ?  model($this->table) : (is_string($dbQuery) ? model($dbQuery) : $dbQuery);
        $map = $search = array();
        $data = [];
        foreach($this->request->param() as $k => $v){
            if(substr($k, 0, 1) == '_'){
                $data[ substr($k,1) ] = ['rule'=>'like','value' => $v];
            }else{
                $data[$k] = $v;
            }
        }
        $tableFields = array_intersect($mod->getTableFields(),array_keys($data));
        foreach ($tableFields as $key => $val) {
            if (substr($key, 0, 1) == '_') {
                continue;
            }
            if ($data[$val]) {
                if(is_array($data[$val])){
                    $map[$val] = array($data[$val]['rule'],"%{$data[$val]['value']}%");
                    $search[$val] = $data[$val]['value'];
                }else{
                    $map[$val] = $data[$val];
                    $search[$val] = $data[$val];
                }
                $search[$val] = $data[$val];
            }
        }
        $this->assign('search', $search);
        $this->_callback('_after_search', $map);

        return $map;
    }
    //异步 修改字段
    public function ajax_edit(){
        $db = Db::name($this->table);
        $data =$this->request->post();
        if(isset($data) && is_array($data) && !empty($data) && $data['id'] && $data['field']){
            $pk = $db->getPk();
            $db->where([$pk => $data['id']])->setField($data['field'],$data['val']);
        }
        $this->result('',1);
    }

    /**
     * 删除
     */
    public function delete(){
        $db = Db::name($this->table);
        $pk = $db->getPk();
        $data =$this->request->post();
        $ids = explode(',', $data['id']);
        $where[empty($pk) ? 'id' : $pk] = ['in', $ids];
        if(false !== $db->where($where)->delete()){
            return json(['code' => 1 ,'msg' => '操作成功']);
        }else{
            return json(['code' => 0 ,'msg' => '操作失败']);
        }
    }

    public function upfile(){
        if (!in_array(($uptype = $this->request->get('uptype')), ['local', 'qiniu', 'oss'])) {
            $uptype = sysconf('storage_type');
        }
        $types = $this->request->get('type', 'jpg,png');
        $mode = $this->request->get('mode', 'one');
        $this->assign('mimes', FileService::getFileMine($types));
        $this->assign('field', $this->request->get('field', 'file'));
        return view('common@admin/upfile', ['mode' => $mode, 'types' => $types, 'uptype' => $uptype]);
    }

    public function icon(){
        $field = $this->request->get('field', 'icon');
        return view('common@admin/icon', ['field' => $field]);
    }
    /**
     * 当前对象回调成员方法
     * @param string $method
     * @param array|bool $data
     * @return bool
     */
    protected function _callback($method, &$data) {
        foreach ([$method, "{$method}_" . $this->request->action()] as $_method) {
            if (method_exists($this, $_method) && false === $this->$_method($data)) {
                return false;
            }
        }
        return true;
    }


    /**
     * 后台主菜单权限过滤
     * @param array $menus
     * @return array
     */
    protected function _filterMenu($menus)
    {
        foreach ($menus as $key => &$menu) {
            if (!empty($menu['sub'])) {
                $menu['sub'] = $this->_filterMenu($menu['sub']);
            }
            if (!empty($menu['sub'])) {
                $menu['url'] = '#';
            } elseif (stripos($menu['url'], 'http') === 0) {
                continue;
            } elseif ($menu['url'] !== '#' && auth(join('/', array_slice(explode('/', $menu['url']), 0, 3)))) {
                $menu['url'] = url($menu['url']);
            } else {
                unset($menus[$key]);
            }
        }
        return $menus;
    }
}
